package fun.ticsmyc.multiThread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Ticsmyc
 * @package fun.ticsmyc.multiThread
 * @date 2020-08-04 08:55
 */
public class 手写自旋锁 {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() +"尝试上锁");
        while(!atomicReference.compareAndSet(null,thread)){
            System.out.print(".");
        }
        System.out.println(thread.getName() +"成功");
    }

    public void unlock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() +"尝试解锁");
        atomicReference.compareAndSet(thread,null);
        System.out.println(thread.getName() +"解锁成功");
    }

    public static void main(String[] args) {
        手写自旋锁 lock = new 手写自旋锁();
        new Thread(()->{
            lock.lock();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
        },"t1").start();
        new Thread(()->{
            lock.lock();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
        },"t2").start();
    }
}
